<template>
	<view class="chatroom-page">
		<!-- 顶部搜索栏 -->
		<view class="header">
			<view class="search-bar">
				<up-search shape="round" v-model="searchValue" @search="searchChatroom" @clear="searchClear"
					placeholder="搜索聊天室" :clearabled="true"></up-search>
			</view>
			<!-- 			<view class="create-btn" @click="handleCreateRoom">
				<up-icon name="plus-circle" size="20" color="#fff"></up-icon>
			</view> -->
		</view>

		<!-- 聊天室列表 -->
		<view class="chatroom-content">
			<scroll-view scroll-y class="scroll-container" @scrolltolower="loadMore" :refresher-enabled="true"
				:refresher-triggered="refreshing" @refresherrefresh="onRefresh" @refresherrestore="onRestore"
				v-if="!loading">
				<!-- 骨架屏 -->
				<view class="skeleton-container" v-if="loading && chatrooms.length === 0">
					<view class="skeleton-item" v-for="i in 5" :key="i">
						<view class="skeleton-avatar skeleton-animate"></view>
						<view class="skeleton-content">
							<view class="skeleton-title skeleton-animate"></view>
							<view class="skeleton-text skeleton-animate"></view>
						</view>
					</view>
				</view>

				<!-- 聊天室列表 -->
				<view class="chatroom-list" v-else-if="chatrooms && chatrooms.length > 0">
					<view class="chatroom-item" v-for="room in chatrooms" :key="room.roomId"
						@click="handleRoomClick(room.roomId)">
						<view class="room-avatar">
							<image :src="room.avatar" mode="aspectFill" />
							<view class="online-badge" v-if="room.onlineCount > 0">
								{{ room.onlineCount }}
							</view>
						</view>
						<view class="room-info">
							<view class="room-header">
								<text class="room-name">{{ room.roomName }}</text>
								<text class="last-time">{{ formatTime(room.lastMessageTime) }}</text>
							</view>
							<view class="room-footer">
								<text class="last-message">{{ room.lastMessage }}</text>
								<view class="unread-badge" v-if="room.unreadCount > 0">
									{{ room.unreadCount > 99 ? '99+' : room.unreadCount }}
								</view>
							</view>
						</view>
					</view>

					<!-- 加载更多提示 -->
					<view class="load-more" v-if="hasMore">
						<up-loading-icon v-if="loadingMore" size="20" />
						<text v-else class="load-more-text">上拉加载更多</text>
					</view>
					<view class="no-more" v-else>
						<text class="no-more-text">没有更多了</text>
					</view>
				</view>

				<!-- 空状态 -->
				<view class="empty-state" v-else-if="!loading && chatrooms.length === 0">
					<up-icon name="chat" size="80" color="#cccccc"></up-icon>
					<text class="empty-text">暂无聊天室</text>
					<text class="empty-hint">点击右上角创建一个聊天室吧～</text>
				</view>
			</scroll-view>
		</view>

		<!-- 创建聊天室弹窗 -->
		<up-popup v-model:show="showCreatePopup" mode="center" :round="10">
			<view class="create-popup">
				<view class="popup-title">创建聊天室</view>
				<view class="popup-content">
					<view class="form-item">
						<text class="label">聊天室名称</text>
						<input class="input" v-model="newRoomName" placeholder="请输入聊天室名称" maxlength="20" />
					</view>
					<view class="form-item">
						<text class="label">聊天室简介</text>
						<textarea class="textarea" v-model="newRoomDesc" placeholder="请输入聊天室简介（可选）" maxlength="100" />
					</view>
				</view>
				<view class="popup-footer">
					<view class="btn btn-cancel" @click="showCreatePopup = false">取消</view>
					<view class="btn btn-confirm" @click="handleConfirmCreate">创建</view>
				</view>
			</view>
		</up-popup>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		mockGetChatrooms,
		mockCreateChatroom
	} from '../../server/mock.js';
	import {
		sendWebsocket
	} from '../../utils/websocket.js'
	import {
		getChatrooms
	} from '../../server/api/chatroom.js';

	// 响应式数据
	const searchValue = ref('');
	const chatrooms = ref([]);
	const loading = ref(true);
	const loadingMore = ref(false);
	const hasMore = ref(true);
	const pageNum = ref(1);
	const pageSize = ref(20);
	const refreshing = ref(false);
	const showCreatePopup = ref(false);
	const newRoomName = ref('');
	const newRoomDesc = ref('');

	// 页面加载时获取数据
	onLoad(() => {
		getChatroomList();
	});

	/**
	 * 获取聊天室列表
	 */
	const getChatroomList = async () => {
		try {
			const params = {
				pageNum: pageNum.value,
				pageSize: pageSize.value,
				roomName: searchValue.value || undefined
			};

			const res = await getChatrooms(params);

			if (res.code === 200) {
				const newChatrooms = res.data || [];

				if (pageNum.value === 1) {
					chatrooms.value = newChatrooms;
				} else {
					chatrooms.value.push(...newChatrooms);
				}

				// 新增：更新hasMore状态，避免重复加载
				hasMore.value = chatrooms.value.length < (res.data?.length || 0);
			}
		} catch (error) {
			console.error('获取聊天室列表失败:', error);
			if (pageNum.value === 1) {
				chatrooms.value = [];
			}
		} finally {
			loading.value = false;
		}
	};

	/**
	 * 搜索聊天室
	 */
	const searchChatroom = () => {
		pageNum.value = 1;
		hasMore.value = true;
		getChatroomList();
	};

	/**
	 * 清除搜索
	 */
	const searchClear = () => {
		searchValue.value = '';
		pageNum.value = 1;
		hasMore.value = true;
		getChatroomList();
	};


	/**
	 * 点击聊天室
	 */
	const handleRoomClick = (roomId) => {
		uni.navigateTo({
			url: `/pages/chatroom/chatroomDetail?roomId=${roomId}`
		});
	};

	/**
	 * 加载更多
	 */
	const loadMore = () => {
		if (!hasMore.value || loadingMore.value || loading.value) return;

		loadingMore.value = true;
		pageNum.value += 1;
		getChatroomList().finally(() => {
			loadingMore.value = false;
		});
	};

	/**
	 * 下拉刷新
	 */
	const onRefresh = async () => {
		refreshing.value = true;
		pageNum.value = 1;
		hasMore.value = true;

		try {
			await getChatroomList();
		} finally {
			setTimeout(() => {
				refreshing.value = false;
			}, 300);
		}
	};

	/**
	 * 刷新恢复
	 */
	const onRestore = () => {
		refreshing.value = false;
	};

	/**
	 * 创建聊天室
	 */
	const handleCreateRoom = () => {
		showCreatePopup.value = true;
		newRoomName.value = '';
		newRoomDesc.value = '';
	};

	/**
	 * 确认创建
	 */
	const handleConfirmCreate = async () => {
		if (!newRoomName.value.trim()) {
			uni.showToast({
				title: '请输入聊天室名称',
				icon: 'none'
			});
			return;
		}

		try {
			uni.showLoading({
				title: '创建中...'
			});

			const res = await mockCreateChatroom({
				roomName: newRoomName.value.trim(),
				roomDesc: newRoomDesc.value.trim()
			});

			uni.hideLoading();

			if (res.code === 200) {
				uni.showToast({
					title: '创建成功',
					icon: 'success'
				});
				showCreatePopup.value = false;

				// 刷新列表
				pageNum.value = 1;
				hasMore.value = true;
				getChatroomList();
			} else {
				uni.showToast({
					title: res.message || '创建失败',
					icon: 'none'
				});
			}
		} catch (error) {
			uni.hideLoading();
			console.error('创建聊天室失败:', error);
			uni.showToast({
				title: '创建失败',
				icon: 'none'
			});
		}
	};

	/**
	 * 格式化时间
	 */
	const formatTime = (timestamp) => {
		if (!timestamp) return '';

		const now = Date.now();
		const diff = now - timestamp;
		const minute = 60 * 1000;
		const hour = 60 * minute;
		const day = 24 * hour;

		if (diff < minute) {
			return '刚刚';
		} else if (diff < hour) {
			return `${Math.floor(diff / minute)}分钟前`;
		} else if (diff < day) {
			return `${Math.floor(diff / hour)}小时前`;
		} else if (diff < 2 * day) {
			return '昨天';
		} else {
			const date = new Date(timestamp);
			return `${date.getMonth() + 1}-${date.getDate()}`;
		}
	};
</script>

<style lang="scss" scoped>
	@import '../../styles/variables.scss';
	@import '../../styles/mixins.scss';

	.chatroom-page {
		width: 100%;
		height: 100vh;
		background: linear-gradient(180deg, #f8f9fa 0%, #e9ecef 100%);
		box-sizing: border-box;
		overflow: hidden;
	}

	// 顶部栏
	.header {
		height: 70px;
		display: flex;
		align-items: center;
		padding: $spacing-base;
		background: #fff;
		border-bottom: 1px solid rgba(0, 0, 0, 0.06);
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.03);
		z-index: 10;
		box-sizing: border-box;

		.search-bar {
			flex: 1;
			margin-right: $spacing-base;
		}

		.create-btn {
			width: 42px;
			height: 42px;
			flex-shrink: 0;
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;
			transition: all $transition-base;
			box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);

			&:active {
				transform: scale(0.92);
				box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
			}
		}
	}

	// 内容区
	.chatroom-content {
		height: calc(100vh - 70px);
		overflow-y: auto;
		-webkit-overflow-scrolling: touch;

		.scroll-container {
			width: 100%;
			height: 100%;
			box-sizing: border-box;
		}
	}

	// 骨架屏
	.skeleton-container {
		padding: $spacing-base;

		.skeleton-item {
			display: flex;
			padding: $spacing-lg;
			margin-bottom: $spacing-base;
			background: #fff;
			border-radius: $radius-lg;
			box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
			border: 1px solid rgba(0, 0, 0, 0.04);

			.skeleton-avatar {
				width: 56px;
				height: 56px;
				border-radius: 50%;
				background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
				background-size: 200% 100%;
				flex-shrink: 0;
			}

			.skeleton-content {
				flex: 1;
				margin-left: $spacing-base;
				display: flex;
				flex-direction: column;
				justify-content: center;

				.skeleton-title {
					height: 18px;
					width: 60%;
					margin-bottom: $spacing-sm;
					background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
					background-size: 200% 100%;
					border-radius: $radius-sm;
				}

				.skeleton-text {
					height: 14px;
					width: 80%;
					background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
					background-size: 200% 100%;
					border-radius: $radius-sm;
				}
			}
		}
	}

	.skeleton-animate {
		animation: skeleton-loading 1.5s ease-in-out infinite;
	}

	@keyframes skeleton-loading {
		0% {
			background-position: 200% 0;
		}

		100% {
			background-position: -200% 0;
		}
	}

	// 聊天室列表
	.chatroom-list {
		padding: $spacing-base;

		.chatroom-item {
			display: flex;
			padding: $spacing-lg;
			margin-bottom: $spacing-base;
			background: #fff;
			border-radius: $radius-lg;
			transition: all $transition-base;
			cursor: pointer;
			box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
			border: 1px solid rgba(0, 0, 0, 0.04);
			animation: fadeInUp 0.3s ease-out backwards;

			&:nth-child(1) {
				animation-delay: 0s;
			}

			&:nth-child(2) {
				animation-delay: 0.05s;
			}

			&:nth-child(3) {
				animation-delay: 0.1s;
			}

			&:nth-child(4) {
				animation-delay: 0.15s;
			}

			&:nth-child(5) {
				animation-delay: 0.2s;
			}

			&:active {
				transform: scale(0.98);
				box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
			}

			&:last-child {
				margin-bottom: 0;
			}

			.room-avatar {
				width: 56px;
				height: 56px;
				position: relative;
				flex-shrink: 0;

				image {
					width: 100%;
					height: 100%;
					border-radius: 50%;
					border: 2px solid #f8f9fa;
					box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
				}

				.online-badge {
					position: absolute;
					top: -4px;
					right: -4px;
					min-width: 22px;
					height: 22px;
					padding: 0 6px;
					background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
					color: #fff;
					font-size: 11px;
					font-weight: $font-semibold;
					border-radius: 11px;
					display: flex;
					align-items: center;
					justify-content: center;
					border: 2px solid #fff;
					box-shadow: 0 2px 8px rgba(82, 196, 26, 0.4);
				}
			}

			.room-info {
				flex: 1;
				margin-left: $spacing-base;
				overflow: hidden;
				display: flex;
				flex-direction: column;
				justify-content: center;

				.room-header {
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-bottom: 6px;

					.room-name {
						flex: 1;
						font-size: 16px;
						font-weight: $font-semibold;
						color: $text-primary;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}

					.last-time {
						flex-shrink: 0;
						margin-left: $spacing-sm;
						font-size: 11px;
						color: $text-secondary;
						opacity: 0.8;
					}
				}

				.room-footer {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.last-message {
						flex: 1;
						font-size: $font-sm;
						color: $text-secondary;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
						line-height: 1.4;
					}

					.unread-badge {
						flex-shrink: 0;
						min-width: 20px;
						height: 20px;
						padding: 0 6px;
						margin-left: $spacing-sm;
						background: linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%);
						color: #fff;
						font-size: 11px;
						font-weight: $font-semibold;
						border-radius: 10px;
						display: flex;
						align-items: center;
						justify-content: center;
						box-shadow: 0 2px 8px rgba(255, 77, 79, 0.4);
					}
				}
			}
		}
	}

	@keyframes fadeInUp {
		from {
			opacity: 0;
			transform: translateY(20px);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	// 加载更多/没有更多
	.load-more,
	.no-more {
		padding: $spacing-lg 0;
		text-align: center;

		.load-more-text,
		.no-more-text {
			font-size: $font-sm;
			color: $text-secondary;
		}
	}

	// 空状态
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100px $spacing-base;

		.empty-text {
			margin-top: $spacing-xl;
			font-size: 18px;
			font-weight: $font-medium;
			color: $text-primary;
		}

		.empty-hint {
			margin-top: $spacing-sm;
			font-size: $font-sm;
			color: $text-secondary;
			opacity: 0.8;
		}
	}

	// 创建聊天室弹窗
	.create-popup {
		width: 320px;
		background: #fff;
		border-radius: $radius-xl;
		overflow: hidden;
		box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);

		.popup-title {
			padding: $spacing-xl $spacing-lg;
			text-align: center;
			font-size: 18px;
			font-weight: $font-semibold;
			color: $text-primary;
			background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
			border-bottom: 1px solid rgba(0, 0, 0, 0.05);
		}

		.popup-content {
			padding: $spacing-xl $spacing-lg;

			.form-item {
				margin-bottom: $spacing-lg;

				&:last-child {
					margin-bottom: 0;
				}

				.label {
					display: block;
					margin-bottom: $spacing-sm;
					font-size: $font-sm;
					font-weight: $font-medium;
					color: $text-primary;
				}

				.input,
				.textarea {
					width: 100%;
					padding: 10px $spacing-base;
					background: #f8f9fa;
					border: 1px solid transparent;
					border-radius: $radius-base;
					font-size: $font-base;
					color: $text-primary;
					transition: all $transition-fast;

					&::placeholder {
						color: $text-disabled;
					}

					&:focus {
						background: #fff;
						border-color: rgba(102, 126, 234, 0.3);
						box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.05);
					}
				}

				.textarea {
					min-height: 80px;
					resize: none;
					font-family: inherit;
				}
			}
		}

		.popup-footer {
			display: flex;
			padding: $spacing-base;
			gap: $spacing-base;
			background: #f8f9fa;

			.btn {
				flex: 1;
				padding: $spacing-sm $spacing-base;
				text-align: center;
				font-size: $font-base;
				font-weight: $font-medium;
				cursor: pointer;
				transition: all $transition-base;
				border-radius: $radius-base;

				&.btn-cancel {
					background: #fff;
					color: $text-secondary;
					border: 1px solid rgba(0, 0, 0, 0.1);

					&:active {
						background: #f8f9fa;
					}
				}

				&.btn-confirm {
					background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
					color: #fff;
					border: none;
					box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);

					&:active {
						transform: translateY(1px);
						box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
					}
				}
			}
		}
	}
</style>

<style lang="scss">
	// 页面级别样式（非 scoped）
	page {
		height: 100%;
		overflow: hidden;
	}
</style>